import {
  getAllRole,
  getPermissionTree,
  updateRole,
  setPeople
} from "@/api/role";
import { searchAccount } from "@/api/account";
// 权限判断指令
import permission from "@/directive/permission/index.js";

const defaultRole = {
  name: "",
  codename: "",
  permissions: []
};

export default {
  directives: { permission },
  data() {
    return {
      options: [],
      listQuery: {},
      role: Object.assign({}, defaultRole),
      rolesList: [],
      dialogVisible: false,
      dialogSetVisible: false,
      dialogAddVisible: false,
      dialogType: "create",
      checkStrictly: false,
      // 权限树
      permissionTree: [],
      defaultProps: {
        children: "child",
        label: "name"
      },
      rules: {
        name: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      getAllRole(this.listQuery).then(response => {
        this.rolesList = response;
      });
      this.getPermissionTree();
    },
    async getPermissionTree() {
      const res = await getPermissionTree();
      this.permissionTree = res;
    },

    showUpdateDialog(row) {
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([]);
      }
      // 保存一份初始的数据, 方便提交的时候进行对比, 只更新已经修改过的字段
      this.originRole = JSON.parse(JSON.stringify(row)); // 深拷贝, 不能Object.assign, 因为row是两层
      this.role = row;
      this.dialogType = "update";
      this.dialogVisible = true;
      this.$nextTick(function() {
        row.permissions.forEach(i => {
          const node = this.$refs.tree.getNode(i);
          if (node && node.isLeaf) {
            this.$refs.tree.setChecked(node, true);
          }
        });
      });
    },

    formatData(data) {
      for (var key in data) {
        if (data[key] === "") {
          data[key] = undefined;
        }
      }
    },

    // 进行更新角色
    updateData() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 只传修改了的字段
          if (this.originRole.name === this.role.name) {
            this.role.name = undefined;
          }
          if (this.originRole.codename === this.role.codename) {
            this.role.codename = undefined;
          }
          const halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
          const checkedKeys = this.$refs.tree.getCheckedKeys();
          this.role.permissions = halfCheckedKeys.concat(checkedKeys);
          var tmp1 = this.role.permissions.sort().toString();
          var tmp2 = this.originRole.permissions.sort().toString();
          if (tmp1 === tmp2) {
            this.role.permissions = [];
          }

          updateRole(this.role.id, this.role).then(response => {
            // const index = this.rolesList.findIndex(v => v.id === this.role.id);
            // this.rolesList.splice(index, 1, response);
            getAllRole(this.listQuery).then(response => {
              this.rolesList = response;
            });
            this.dialogVisible = false;
            this.$notify({
              title: "更新成功",
              message: "成功更新" + response.name + "的权限",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },

    setData() {
      setPeople(this.role.id, { person: this.role.person })
        .then(res => {
          this.$notify({
            title: "更新成功",
            message: "设置成功",
            type: "success",
            duration: 2000
          });

          this.dialogSetVisible = false;
        })
        .catch(res => {
          this.$notify({
            title: "更新失败",
            message: res.response.data.message,
            type: "error",
            duration: 2000
          });
        });
    },

    showSetDialog(row) {
      this.dialogSetVisible = true;
      this.role = row;
      let id = row.person;
      let name = row.person_name.split(",");
      this.options = [];
      for (let i = 0; i < id.length; i++) {
        this.options.push({ id: id[i], realname: name[i] });
      }
    },

    // del(row) {},
    searchAccount(e) {
      if (!e) return;
      searchAccount({ realname: e }).then(response => {
        this.options = response;
      });
    },

    showAddDialog() {
      this.dialogAddVisible = true;
      this.role = {};
    }
  }
};
